<template>
  <div class="employees-container">
    <div class="app-container">
      <headTool>
        <!-- 插槽传递结构给headTool组件 -->
        <template #after>
          <el-button type="success" @click="exportExcel">导出</el-button>
          <el-button type="primary" @click="$router.push({ path: '/import' })"
            >导入</el-button
          >
          <!-- 新增员工 -->
          <el-button type="primary" @click="showDialog = true">
            + 新增员工</el-button
          >
        </template>
      </headTool>
      <el-card>
        <!-- table表格 -->
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="180" />
          <!-- 头像处理 -->

          <el-table-column prop="staffPhoto" label="头像" width="180">
            <div slot-scope="{ row }" class="avator">
              <img
                @click="showQrcode(row.staffPhoto)"
                v-imgerror="defaultImg"
                :src="row.staffPhoto"
                alt=""
                style="width:120px;height:120px;overflow:hidden;border:2px solid skyblue;border-radius:80px"
              />
            </div>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="180" />
          <el-table-column prop="mobile" label="手机号" width="180" />
          <el-table-column prop="workNumber" label="工号" width="180" />
          <el-table-column prop="formOfEmployment" label="聘用形式" width="180">
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" width="180" />

          <el-table-column prop="timeOfEntry" label="入职时间" width="180">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <!-- 请求不到状态？？？ -->
          <!-- <el-table-column prop="name" label="状态" width="180">
            <template slot-scope="{ row }">
              <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column> -->
          <el-table-column fixed="right" label="操作" width="280">
            <div slot-scope="{ row }">
              <el-link
                type="primary"
                @click="
                  $router.push({
                    path: '/employees/detail',
                    query: { id: row.id }
                  })
                "
                >查看</el-link
              >
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary" @click="showRole(row.id)">角色</el-link>
              <!-- 给删除添加点击事件 -->
              <el-link type="primary" @click="delEmp(row.id)">删除</el-link>
            </div>
          </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handlePage"
          layout="total,prev, pager, next"
          :total="pageInfo.total"
          :page-size="pageInfo.size"
          :current-page="pageInfo.page"
        >
        </el-pagination>
        <!-- 二维码dialog -->
        <el-dialog title="头像二维码" :visible.sync="isShowQrcode" width="80%">
          <el-row type="flex" justify="center">
            <canvas ref="canvas"></canvas>
          </el-row>
        </el-dialog>
      </el-card>
      <addEmp :showDialog="showDialog" @closeDialog="closeDialog"></addEmp>
      <!-- 角色分配 -->
      <roleSet
        ref="roleSet"
        :showRoleDialog.sync="showRoleDialog"
        :userId="currentId"
      ></roleSet>
    </div>
  </div>
</template>

<script>
// 导入二维码插件
import qrcode from 'qrcode'
// 分配角色
import roleSet from './components/role-setting.vue'

import addEmp from './components/addEmp.vue'
// 角色列表api
import { getRoleListDetail } from '@/api/setting'
import constant from '@/api/constant/employees'
import { delEmp } from '@/api/emloyees'
import { formatDate } from '@/filters'
export default {
  components: {
    addEmp,
    roleSet
  },
  filters: {
    /* eslint-disable */
    formatHireType (val) {
      const list = constant.hireType.filter(item => item.id == val)
      return list[0] ? list[0].value : '未知'
    }
  },
  data () {
    return {
      showRoleDialog: false,
      currentId: '',
      isShowQrcode: false,
      // value: true,
      defaultImg: require('@/assets/common/head.jpg'),
      tableData: [],
      pageInfo: {
        page: 1,
        size: 5,
        total: 0
      },
      showDialog: false
    }
  },

  async created () {
    await this.getList()
  },
  methods: {
    // 分配角色
    async showRole (id) {
      this.currentId = id
      this.showRoleDialog = true
      await this.$refs.roleSet.getuserprofile(id)
    },
    // 点击头像显示二维码
    // 点击头像，显示dialog，dialog里包含二维码，注意有判断有图片时，显示dialog，没有时，发出警告
    showQrcode (imgUrl) {
      if (imgUrl) {
        this.isShowQrcode = true
        // 下一次dom更新时调用
        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.canvas, imgUrl)
        })
      } else {
        this.$message.warning('该员工暂无图片')
      }
    },
    // 导出excel
    async exportExcel () {
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 发起请求，获得所有员工的信息
      const res = await getRoleListDetail({
        page: 1,
        size: this.pageInfo.total
      })
      // console.log('res:', res)

      const list = res.data.rows
      // 获取所有的key,中文表头
      let keys = Object.keys(headers)
      // console.log(keys)
      // 内容
      // console.log('list:', list)
      const bigArr = list.map(item => {
        // item是list里的每一个对象
        const arr = []
        for (let key in headers) {
          // 遍历headers,将headers的值作为item的键
          let engKey = headers[key]
          if (key == '入职日期' || key == '转正日期') {
            const time = formatDate(item[engKey])
            arr.push(time)
          } else if (key == '聘用形式') {
            const str = item[engKey] == 1 ? '正式' : '未知'
            arr.push(str)
          } else {
            // 将item中函数headers值的值添加到数组里
            arr.push(item[engKey])
          }
        }
        return arr
      })
      // console.log('bigArr:', bigArr)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: keys, //表头 必填
          data: bigArr, //具体数据 必填
          filename: '员工列表', //非必填
          autoWidth: true, //非必填
          bookType: 'xlsx' //非必填
        })
      })
    },
    async getList () {
      const res = await getRoleListDetail(this.pageInfo)
      console.log('res:', res)
      this.pageInfo.total = res.data.total
      this.tableData = res.data.rows
      console.log(this.tableData)
    },
    // 分页改变触发事件
    handlePage (v) {
      // 这里的参数是组件默认的
      this.pageInfo.page = v

      // 刷新页面
      this.getList()
    },
    // 删除员工
    async delEmp (id) {
      // 确认是否删除
      try {
        await this.$confirm('确认删除吗？')
        // 发起删除请求
        await delEmp(id)
        // 成功提示
        this.$message.success('删除成功！')
        // 如果最后一页的数据只有一条，删除后，page应该减1,且不应该为第一页
        if (this.tableData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--
        }
        // 更新页面
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 改变子组件对话框的状态
    // changeDialog () {
    //   this.showDialog = true
    // }
    // 隐藏对话框
    closeDialog () {
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .avator {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-card {
    margin: 20px;
    .el-link {
      margin: 0 5px;
    }
  }

  .el-pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
